package cn.edu.nankai.bookstore.service.impl;


import cn.edu.nankai.bookstore.dao.BookDao;
import cn.edu.nankai.bookstore.dao.ItemDao;
import cn.edu.nankai.bookstore.dao.OrderDao;
import cn.edu.nankai.bookstore.dao.impi.BookDaoImpl;
import cn.edu.nankai.bookstore.dao.impi.ItemDaoImpl;
import cn.edu.nankai.bookstore.dao.impi.OrderDaoImpl;
import cn.edu.nankai.bookstore.domain.po.Item;
import cn.edu.nankai.bookstore.domain.po.Order;
import cn.edu.nankai.bookstore.service.OrderService;

import java.util.List;

public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private ItemDao itemDao = new ItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    public List<Order> getAll() {
        return orderDao.findAll();
    }

    public List<Order> getByCustomerId(int customerId) {
        return orderDao.findAllByCustomerId(customerId);
    }

    public Order getById(int orderId) {
        return orderDao.findById(orderId);
    }

    public Order create(int customerId, int receiverId){
        Order order = new Order(customerId,null,receiverId,0.0,0.0,false);
        int id = orderDao.insert(order);
        return orderDao.findById(id);
    }
    public boolean addItem(Order order, Item item) {
        item.setOrderId(order.getOrderId());
        item.setTotal(bookDao.findById(item.getBookId()).getPrice() * item.getAmount());
        item.setDiscountTotal(item.getTotal() * item.getDiscount());
        order.setTotalPrice(order.getTotalPrice() + item.getTotal());
        order.setDiscountTotalPrice(order.getDiscountTotalPrice() + item.getDiscountTotal());
        orderDao.update(order);
        return itemDao.insert(item) != 0;
    }

    @Override
    public boolean removeItem(Order order, int bookId) {
        List<Item> items = itemDao.findAllByOrderId(order.getOrderId());
        for (Item item : items) {
            if(item.getBookId() == bookId){
                order.setTotalPrice(order.getTotalPrice() - item.getTotal());
                order.setDiscountTotalPrice(order.getDiscountTotalPrice() - item.getDiscountTotal());
                orderDao.update(order);
                return itemDao.delete(item) != 0;
            }
        }
        return false;
    }

    @Override
    public boolean submit(Order order) {
        order.setSubmitted(true);
        return orderDao.update(order) != 0;
    }

    public boolean remove(int id) {
        List<Item> items = itemDao.findAllByOrderId(id);
        for (Item item : items) {
            itemDao.delete(item);
        }
        return orderDao.delete(id) != 0;
    }

}
